<template>
    <div>
        <!-- 面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row>
                <el-button type="primary" @click="() => {addRoleDialogVisible = true}">添加角色</el-button>
            </el-row>

            <!-- 角色列表 -->
            <el-table :data="roleList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1, i1) in scope.row.children"
                            :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                                <el-row v-for="(item2, i2) in item1.children" :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                                    :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{
                                            item2.authName }}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable
                                            @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index">
                </el-table-column>
                <el-table-column prop="roleName" label="名称">
                </el-table-column>
                <el-table-column prop="roleDesc" label="描述">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                        <el-button @click="delRole(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                        <el-button @click="openRights(scope.row)" size="mini" type="warning"
                            icon="el-icon-setting">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-card>

        <!-- 添加角色的对话框 -->
        <el-dialog :close-on-click-modal="false" title="添加角色" :visible.sync="addRoleDialogVisible" width="50%"
            @close="() => { addRoleDialogVisible = false }">
            <!-- 内容主体区域 -->
            <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限的对话框 -->
        <el-dialog :close-on-click-modal="false" title="分配权限" :visible.sync="rightsDialogVisible" width="50%"
            @close="() => { rightsDialogVisible = false }">
            <!-- 内容主体区域 -->
            <el-tree ref="rightsListRef" :data="rightsList" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys" :props="defaultProps">
            </el-tree>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="rightsDialogVisible = false">取 消</el-button>
                <el-button @click="saveRights" type="primary">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>

export default {
    data() {
        return {
            roleList: [],
            rightsDialogVisible: false,
            rightsList: [], // 用于保存权限点
            defKeys: [], // tree的默认选中项
            defaultProps: {
                label: 'authName',
                children: 'children'
            },
            setId: null,
            addRoleDialogVisible: false,
            addRoleForm: {
                roleName: '',
                roleDesc: '',
            },
            addRoleFormRules: {
                roleName: [
                { required: true, message: "请输入角色名", trigger: "blur" },
                ]
            }

        }
    },
    created() {
        this.getRoles()
    },
    methods: {
        // 获取角色列表
        async getRoles() {
            const res = await this.$http.get('roles')
            console.log(res);
            if (res.status == 200) {
                this.roleList = res.data.data
            }
        },

        // 打开分配权限的设置弹窗
        async openRights(role) {
            // 设置需要修改权限的当前角色
            this.setId = role.id
            // 先清空权限点
            this.defKeys = []

            // 请求所有的权限点列表
            const res = await this.$http.get('rights/tree')
            // console.log(res);
            if (res.status == 200) {
                this.rightsList = res.data.data
            }

            // 需要把当前角色的权限点勾上
            // 递归拿到自己的权限点
            this.getLeafKeys(role, this.defKeys)

            this.rightsDialogVisible = true
        },

        getLeafKeys(nodes, arr) {
            // console.log(nodes);
            if (!nodes.children) return arr.push(nodes.id)
            nodes.children.forEach(item => this.getLeafKeys(item, arr))
        },

        // 删除权限点
        removeRightById(row, rid) {
            this.$confirm('确认删除该权限吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 发送删除请求
                const res = await this.$http.delete(`roles/${row.id}/rights/${rid}`)
                // console.log(res);
                if (res.status == 200) {
                    this.getRoles()
                    this.$message.success('删除成功')
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            })
        },

        // 保存权限
        async saveRights() {
            // console.log(this.$refs.rightsListRef.getCheckedKeys());
            // console.log(this.$refs.rightsListRef.getHalfCheckedKeys());
            const keys = [
                ...this.$refs.rightsListRef.getCheckedKeys(),
                ...this.$refs.rightsListRef.getHalfCheckedKeys()
            ]

            const rids = keys.join(',')

            const res = await this.$http.post(`roles/${this.setId}/rights`, { rids })

            // console.log(res);
            if (res.status !== 200) {
                this.$message.error('修改失败，请联系管理员')
            }

            // 刷新数据
            this.getRoles()

            this.$message.success('修改成功')

            this.rightsDialogVisible = false
        },

        // 添加角色
        addRole() {
            this.$refs.addRoleFormRef.validate(async valid => {
                if(valid) {
                    const res = await this.$http.post('roles', this.addRoleForm)

                    // console.log(res);
                    if(res.status !== 200) {
                        this.$message.error('添加失败')
                    }

                    this.getRoles()

                    this.$message.success('添加成功')

                    this.addRoleDialogVisible = false
                }
            })
        },

        // 删除角色
        delRole(id) {
            this.$confirm('确认删除该角色吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 发送删除请求
                const res = await this.$http.delete(`roles/${id}`)
                // console.log(res);
                if (res.status == 200) {
                    this.getRoles()
                    this.$message.success('删除成功')
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            })
        }
    }
}
</script>
<style scoped lang="less">
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>